package ro.vikingsoft.androidprj;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author voicuad
 * This class is responsible for creating the database. 
 * The onUpdate() method will simply delete all existing data and re-create the table. 
 * It also defines several constants for the table name and the table columns.
 */
public class MySQLiteHelper extends SQLiteOpenHelper {

	public static final String TABLE_TESTS 				= "TBL_TESTS";
	public static final String COLUMN_TEST_ID 			= "IDTEST";
	public static final String COLUMN_TEST_TITLE 		= "TITLE";

	public static final String TABLE_QUESTIONS 			= "TBL_QUESTIONS";
	public static final String COLUMN_QUESTIONS_ID 		= "IDQUESTION";
	public static final String COLUMN_QUESTIONS_TITLE 	= "TITLE";
	
	private static final String DATABASE_NAME = "resultgrid.db";
	private static final int 	DATABASE_VERSION = 1;
	

	// Database creation sql statement
	private static final String DATABASE_CREATE = 
			"CREATE TABLE "
			+ TABLE_TESTS + "( " 
			+ 	COLUMN_TEST_ID 		+ " integer primary key autoincrement, " 
			+ 	COLUMN_TEST_TITLE 	+ " text not null); " + 
			"CREATE TABLE "
			+ TABLE_QUESTIONS + "( " 
			+ 	COLUMN_QUESTIONS_ID 	+ " integer primary key autoincrement, "
			+ 	COLUMN_TEST_ID 	+ " integer, " // (FK)
			+ 	COLUMN_QUESTIONS_TITLE 	+ " text not null); "
			+ " FOREIGN KEY(" + COLUMN_TEST_ID + ") REFERENCES " + TABLE_TESTS + "("+ COLUMN_TEST_ID +")"
			
			;

	public MySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(DATABASE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w(MySQLiteHelper.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTS);
		onCreate(db);
	}

}
